/*global $Client*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Box, Button, CircularProgress } from '@mui/material';
import { MRT_Localization_ZH_HANS as LocalizationZH } from 'material-react-table/locales/zh-Hans';
import { MaterialReactTable, useMaterialReactTable } from 'material-react-table';
import { usersql } from "../../util/util";
import { useSnackbar } from '../customized/SnackbarProvider'; // 导入自定义的 hook



const App = (pagedata) => {
  const [rowSelection, setRowSelection] = useState({});
  const [tabledata, setTabledata] = useState([]); // 用于存储获取的数据
  const [loading, setLoading] = useState(true); // 用于控制加载状态
  const openSnackbar = useSnackbar();


  //获取数据的函数
  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      console.log('pagedata', pagedata);
      
      let Exportcontractnumberid = pagedata?.data?.data?.Exportcontractnumberid;
      let id1 = pagedata?.data?.data?.id1;
      let modulename = pagedata?.data?.modulename;
      let showsql = pagedata?.data?.showsql;

      
      let responsedata = await usersql(showsql);
      console.log('responsedata', responsedata);
      // let userinfo = await window.ZOHO.CRM.CONFIG.getCurrentUser();
      // let responsedata = await getCrmRecordFromSql(showsql); // 获取数据



      if (responsedata && responsedata.length > 0) {
        setTabledata(responsedata);

        if (modulename === 'CustomModule15') {    //生产发货通知单

          if (Exportcontractnumberid) {
            const ids = Exportcontractnumberid
              ?.split(',')
              .map(id => id.trim())
              .filter(Boolean) || [];

            const initialSelection = responsedata.reduce((selection, item) => {
              if (ids.includes(item.id)) {
                selection[item.id] = true; // 默认勾选
              }
              return selection;
            }, {});
            // console.log('initialSelection', initialSelection);
            setRowSelection(initialSelection);
          }
        } else if (modulename === 'CustomModule17') {   //备货


          if (id1) {
            const ids = id1?.split(',').map(id => id.trim()).filter(Boolean) || [];

            const initialSelection = responsedata.reduce((selection, item) => {
              if (ids.includes(item.id)) {
                selection[item.id] = true; // 默认勾选
              }
              return selection;
            }, {});
            // console.log('initialSelection', initialSelection);
            setRowSelection(initialSelection);
          }
        }
      } else {
        setTabledata([]); // 设置所有数据
      }
    } catch (err) {
      openSnackbar(err, 'error');
      console.error('Error fetching data:', err);
    } finally {
      setLoading(false);
    }
  }, [pagedata, openSnackbar]);

  // 在组件加载时调用 fetchData
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const ok = () => {
    const selectedRows = table.getSelectedRowModel().rows.map(row => row.original);
    const allSameCustomer = selectedRows.every(item => item.Account_Name.id === selectedRows[0].Account_Name.id);
    // console.log('Selected Rows:', selectedRows);
    if (!allSameCustomer) {
      openSnackbar(`请确保选择的合同都属于同一个客户！`, 'warning');
    } else {
      $Client.close({ "selectedRows": selectedRows });
    }
  }

  // { accessorKey: 'Product_Name.name', header: '商品库名称', minSize: 100, enableEditing: false, },

  const columns = useMemo(() => [
    { accessorKey: 'Subject', header: '编号', minSize: 120, size: 120, enableEditing: false, },
    { accessorFn: (row) => row?.['Account_Name.Account_Name'], id: 'Account_Name', header: '客户简称', minSize: 120, size: 120, enableEditing: false, },
    { accessorKey: 'ContractDate', header: '合同日期', minSize: 120, size: 120, enableEditing: false, },
    { accessorKey: 'AccountOrderNo', header: '客户订单号', minSize: 120, size: 120, enableEditing: false, },
    { accessorFn: (row) => row?.['Owner.first_name'], id: 'Ownername', header: '所有者', minSize: 120, size: 120, enableEditing: false, },
  ], []);


  const table = useMaterialReactTable({
    columns: columns,
    data: tabledata ?? [],
    enableColumnResizing: true, // 启用列调整大小
    enableStickyHeader: true, // 启用粘性表头
    enableRowSelection: true, // 启用行选择
    enableHiding: false, // 禁用列隐藏
    enableDensityToggle: false, // 禁用密度切换
    enableGlobalFilter: false, // 禁用全局过滤
    positionToolbarAlertBanner: 'bottom',   // 将工具栏警告横幅的位置设置为底部
    enableFullScreenToggle: false, // 禁用全屏按钮
    enableColumnPinning: false, // 启用列固定
    localization: LocalizationZH, // 设置中文
    getRowId: (row) => row.id, // 设置每行的唯一标识
    enableSelectAll: false, // 禁用全选按钮
    initialState: {
      density: 'compact',
      columnPinning: { left: ['mrt-row-select', 'mrt-row-numbers', 'Subject'] },  //'mrt-row-actions',
    },
    muiTableContainerProps: {
      sx: {
        minHeight: '75vh', // 这里设置表格最大高度
        maxHeight: '75vh', // 这里设置表格最大高度
        overflowY: 'auto',  // 启用竖向滚动条
        overflowX: 'auto',  // 启用横向滚动条，横向滚动条默认显示
      },
    },
    onRowSelectionChange: setRowSelection,  // 设置行选择状态
    state: { rowSelection },
    enableRowNumbers: true,
    rowNumberDisplayMode: 'static', // 显示原始行号
    renderTopToolbarCustomActions: ({ table }) => (
      <Box sx={{ display: 'flex', gap: '1rem', p: '4px' }}>
        <Button
          onClick={async () => {
            await ok(); // 调用 ok 函数
          }}
          variant="contained"
          sx={{
            backgroundColor: 'rgb(74, 146, 243)',
          }}
        >
          确定
        </Button>
        <Button
          onClick={() => {
            $Client.close(); // 关闭弹出框
          }}
          variant="outlined"
        >
          取消
        </Button>
      </Box>
    ),
  });

  return (
    <div>
      {loading ? (
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh' // 使加载图标在页面中央
          }}
        >
          <CircularProgress />
        </Box>
      ) : (
        <MaterialReactTable
          table={table} />
      )}
    </div>
  );
};

export default App;
